# coding:utf-8

from . import api
from flask import current_app,g, jsonify, request, session
from ihome.utils.response_code import RET
from ihome.utils.commons import require_login
from ihome.utils.image_storage import storage
from ihome.utils.constains import QINIU_DOMAIN
from ihome.models import User
from ihome import db


@api.route('/user/avatar', methods=["POST"])
@require_login
def set_avatar():
    user_id = g.user_id
    # 获取图片
    image_file = request.files.get('avatar')

    if image_file is None:
        return jsonify(errno=RET.NODATA, errmsg="图片未上传")
    image_file = image_file.read()
    try:
        file_name = storage(image_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片失败")
    # 保存到数据库
    try:
        User.query.filter_by(id=user_id).update({"avatar_url" :file_name})
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")
    avatar_url = QINIU_DOMAIN + file_name

    return jsonify(errno=RET.OK, errmsg="保存成功", data={'avatar_url': avatar_url})


@api.route('/user/name', methods=["PUT"])
@require_login
def changer_user_name():
    id = g.user_id
    print(id)
    req_json = request.get_json()
    if req_json is None:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")
    name = req_json.get('name')
    if name is None:
        return jsonify(errno=RET.PARAMERR, errmsg="名字为空")

    try:
        User.query.filter_by(id=id).update({'name': name})
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")
    session['name'] = name
    return jsonify(errno=RET.OK, errmsg="修改成功", data={'name': name})


# 获取用户信息
@api.route('/user', methods=['GET'])
@require_login
def get_user_login():
    id = g.user_id
    try:
        user = User.query.filter_by(id=id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取用户信息失败")
    if user is None:
        return jsonify(errno=RET.DATAEXIST, errmsg="数据不存在")
    return jsonify(errno=RET.OK, errmsg="ok", data=user.to_dict())
